package com.xvdong.gadget;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Random;

import javax.imageio.ImageIO;

/**
 * Created by xvDong on 2025/5/8.
 *
 * RDS 红绿图随机生成工具
 */
public class DynamicRDSGenerator {
    private static final int WIDTH = 400;          // 图像宽度
    private static final int HEIGHT = 400;         // 图像高度
    private static final int DOTS_DENSITY = 50;    // 点密度（点数/千像素，建议30-80）
    private static final int DISPARITY_RANGE = 16; // 最大视差范围（建议8-24）
    private static final int DOT_SIZE = 3;         // 点尺寸（1-5）
    private static final String SAVE_PATH = System.getProperty("user.home") + "/Desktop/RDS/"; // 保存路径

    // 立体图形参数
    private static final int SHAPE_WIDTH = 100;     // 立体图形宽度
    private static final int SHAPE_HEIGHT = 80;     // 立体图形高度


    public DynamicRDSGenerator() {
    }

    public static void main(String[] args) throws Exception {
        execute();
    }

    public static void execute(){
        try {
            // 创建随机生成器（无固定种子）
            Random rand = new Random();

            // 生成动态参数（每次不同）
            int disparity = 8 + rand.nextInt(DISPARITY_RANGE-8); // 实际视差量
            int shapeX = rand.nextInt(WIDTH - SHAPE_WIDTH);      // 随机水平位置
            int shapeY = rand.nextInt(HEIGHT - SHAPE_HEIGHT);    // 随机垂直位置

            // 生成基础点阵（左右图共享）
            int[][] baseDots = generateBaseDots(rand);

            // 生成立体图对
            generatePair(rand, baseDots, disparity, shapeX, shapeY);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static int[][] generateBaseDots(Random rand) {
        int total = WIDTH * HEIGHT * DOTS_DENSITY / 1000;
        int[][] dots = new int[total][2];
        for(int i=0; i<total; i++){
            dots[i][0] = rand.nextInt(WIDTH);   // X坐标
            dots[i][1] = rand.nextInt(HEIGHT);  // Y坐标
        }
        return dots;
    }

    private static void generatePair(Random rand, int[][] baseDots,
                                     int disparity, int shapeX, int shapeY) throws Exception {
        // 生成左眼（红）图
        BufferedImage leftImg = createImage(baseDots, (x, y) -> {
            if(isInShape(x, y, shapeX, shapeY)) {
                return disparity/2 + rand.nextInt(2); // 添加随机扰动
            }
            return 0;
        }, new Color(255, 60, 60)); // 暖红色

        // 生成右眼（绿）图
        BufferedImage rightImg = createImage(baseDots, (x, y) -> {
            if(isInShape(x, y, shapeX, shapeY)) {
                return -disparity/2 + rand.nextInt(2);
            }
            return 0;
        }, new Color(60, 255, 60)); // 冷绿色

        // 自动创建保存目录
        new File(SAVE_PATH).mkdirs();

        // 添加时间戳保证文件名唯一
        String timestamp = String.valueOf(System.currentTimeMillis());
        ImageIO.write(leftImg, "PNG", new File(SAVE_PATH + "RDS_LEFT_" + timestamp + ".png"));
        ImageIO.write(rightImg, "PNG", new File(SAVE_PATH + "RDS_RIGHT_" + timestamp + ".png"));
    }

    // 判断点是否在立体图形区域内（可扩展为任意形状）
    private static boolean isInShape(int x, int y, int shapeX, int shapeY) {
        return (x >= shapeX && x < shapeX + SHAPE_WIDTH) &&
                (y >= shapeY && y < shapeY + SHAPE_HEIGHT);
    }

    // 图像生成核心方法（带抗锯齿）
    private static BufferedImage createImage(int[][] baseDots,
                                             DotShiftStrategy strategy, Color color) {
        BufferedImage img = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = img.createGraphics();

        // 启用抗锯齿
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);

        // 绘制背景
        g.setColor(new Color(30, 30, 30)); // 深灰背景
        g.fillRect(0, 0, WIDTH, HEIGHT);

        // 绘制所有点
        for(int[] dot : baseDots){
            int shiftedX = dot[0] + strategy.calculateShift(dot[0], dot[1]);
            if(shiftedX <0 || shiftedX >= WIDTH) continue;

            // 添加随机亮度变化
            int variance = (int)(Math.random()*40);
            g.setColor(new Color(
                    Math.min(255, color.getRed() + variance),
                    Math.min(255, color.getGreen() + variance),
                    Math.min(255, color.getBlue() + variance)
            ));

            // 绘制椭圆实现形状随机化
            int sizeVariation = (int)(Math.random()*DOT_SIZE/2);
            g.fillOval(shiftedX, dot[1],
                    DOT_SIZE + sizeVariation,
                    DOT_SIZE + sizeVariation);
        }
        g.dispose();
        return img;
    }

    interface DotShiftStrategy {
        int calculateShift(int x, int y);
    }
}
